package com.yao.club.service.impl;

import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.dto.SysImg;
import com.yao.club.reposittory.SysImageRepository;
import com.yao.club.service.FileUploadService;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.access.path}")
    private String accessPath;

    @Autowired
    private SysImageRepository sysImageRepository;
    
    @Autowired
    private HttpServletRequest request;

    @Override
    public ResponseEntity<String> uploadFile(MultipartFile file) {
        try {
            // 校验文件
            if (file.isEmpty()) {
                return ResponseUtils.failed("上传文件不能为空");
            }

            // 校验文件类型
            String originalFilename = file.getOriginalFilename();
            if (!isValidImageFile(originalFilename)) {
                return ResponseUtils.failed("不支持的文件类型");
            }

            // 生成文件存储路径
            String storagePath = generateStoragePath(originalFilename);
            
            // 确保目录存在
            File directory = new File(storagePath).getParentFile();
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 保存文件
            Path path = Paths.get(storagePath);
            Files.write(path, file.getBytes());

            // 生成访问URL
            String fileUrl = generateFileUrl(storagePath);

            // 保存图片信息到数据库
            SysImg sysImage = new SysImg();
            sysImage.setFilename(originalFilename);
            sysImage.setUrl(fileUrl);
            sysImage.setContentLength(file.getSize());

            // 保存到数据库
            sysImage = sysImageRepository.save(sysImage);

            // 返回图片URL
            return ResponseUtils.success(fileUrl);
            
        } catch (IOException e) {
            return ResponseUtils.failed("文件上传失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<List<String>> uploadMultipleFiles(MultipartFile[] files) {
        List<String> uploadedUrls = new ArrayList<>();
        
        for (MultipartFile file : files) {
            ResponseEntity<String> result = uploadFile(file);
            if (result.getCode() == 200) {
                uploadedUrls.add(result.getData());
            }
        }

        if (uploadedUrls.isEmpty()) {
            return ResponseUtils.failed("没有文件上传成功");
        }

        return ResponseUtils.success(uploadedUrls);
    }

    /**
     * 验证是否为合法的图片文件
     */
    private boolean isValidImageFile(String filename) {
        if (filename == null) {
            return false;
        }
        String ext = filename.toLowerCase();
        return ext.endsWith(".jpg") || ext.endsWith(".jpeg") 
            || ext.endsWith(".png") || ext.endsWith(".gif");
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null) {
            return "";
        }
        int lastDotIndex = filename.lastIndexOf(".");
        if (lastDotIndex == -1) {
            return "";
        }
        return filename.substring(lastDotIndex + 1).toLowerCase();
    }

    /**
     * 生成文件存储路径
     */
    private String generateStoragePath(String originalFilename) {
        // 获取文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        
        // 生成日期路径
        LocalDate now = LocalDate.now();
        String datePath = String.format("%d/%02d/%02d", now.getYear(), now.getMonthValue(), now.getDayOfMonth());
        
        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + extension;
        
        return uploadPath + File.separator + datePath + File.separator + fileName;
    }

    /**
     * 生成文件访问URL
     */
    private String generateFileUrl(String storagePath) {
        // 将存储路径转换为访问URL
        String relativePath = storagePath.substring(uploadPath.length());
        return accessPath + relativePath.replace(File.separator, "/");
    }
} 